import 'package:flutter/material.dart';
import 'package:flutter_bsbdj/bean/user_info.dart';
import 'package:flutter_bsbdj/bmob/bmob/bmob_query.dart';
import 'package:flutter_bsbdj/bmob/bmob/response/bmob_error.dart';
import 'package:flutter_bsbdj/bmob/bmob/table/bmob_user.dart';
import 'package:flutter_bsbdj/utils/constant.dart';
import 'package:flutter_bsbdj/utils/toast.dart';
import 'package:flutter_bsbdj/utils/shared_preferences_util.dart';

class LoginWidget extends StatefulWidget{

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return Login();
  }

}

class Login extends State<LoginWidget>{

  TextEditingController _nameController=TextEditingController();
  TextEditingController _passController=TextEditingController();
  BuildContext _buildContext;

  //登录与注册使用同一个页面，根据isLogin的状态值判断
  bool _isLogin=true;

  bool _getData=false;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    _buildContext=context;
    return Scaffold(
      body: Stack(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(image: AssetImage("images/timg.jpg"),fit: BoxFit.fill)
            ),
          ),
          Container(
            alignment: Alignment.center,
            child: Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border.all(color: Colors.white,width: 2),
                borderRadius: BorderRadius.all(Radius.circular(10))
              ),
              height: 245,
              width: 300,
              padding: EdgeInsets.all(10),
              alignment: Alignment.center,
              child: Column(
                children: <Widget>[
                  Container(
                    alignment: Alignment.center,
                    child: Text("登  录",style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),),
                    margin: EdgeInsets.only(top: 5,bottom: 15),
                  ),
                  Container(
                    height: 50,
                    child: _inputEdit(_nameController, "请输入用户名", "请输入用户名",Icons.person,false),
                  ),
                  Container(
                    height: 50,
                    child: _inputEdit(_passController, "请输入密码", "请输入密码",Icons.lock,true),
                  ),
                  Container(
                    alignment: Alignment.center,
                    child: MaterialButton(onPressed: (){
                      _login();
                    },child: Text(_isLogin?"登      录":"注      册",style: TextStyle(color: Colors.white),),
                      color: Colors.blueAccent,minWidth: 290,),
                  ),
                  Container(
                    height: 20,
                    child: GestureDetector(
                      child: Text(_isLogin?"注      册":"登      录",style: TextStyle(color: Colors.blueAccent),),
                      onTap: (){
                          setState(() {
                            _isLogin=!_isLogin;
                          });
                      },
                    )
                  )
                ],
              ),
            ),
          ),
          _getData?Container(
            alignment: Alignment.center,
            child: Container(
              width: 200,
              height: 200,
              child: Image.asset("images/ic_loading.gif"),
            ),
          ):Container(
            width: 0,
            height: 0,
          )
        ],
      ),
    );
  }

  //输入控件
  TextField _inputEdit(TextEditingController controller,String label,String hint,IconData iconData,bool isPassWord){
    return TextField(
      controller: controller,
      obscureText: isPassWord,
      decoration: InputDecoration(
        icon: Icon(iconData),
          labelText: label,
          hintText: hint,
          border: OutlineInputBorder(
              borderSide: BorderSide(
                  color: Colors.blueAccent,width: 2
              )
          ),
          contentPadding: EdgeInsets.symmetric(vertical: 10,horizontal: 5)
      ),
    );
  }

  void _login() async{
    var name=_nameController.text.toString();
    if(name==null||name.isEmpty){
      Toast.toast(context, "用户名不能为空");
      print("用户名不能为空");
      return;
    }
    var pass=_passController.text.toString();
    if(pass==null||pass.isEmpty){
      Toast.toast(context, "密码不能为空");
      return;
    }

    if(pass.length<6){
      Toast.toast(context, "密码不能小于 6 位");
      return;
    }

    var user=BmobUser();
    user.username=name;
    user.password=pass;
    setState(() {
      _getData=!_getData;
    });
    if(_isLogin) {
      //登录模式，登录
      await user.login().then((bmobUser) {
        SharedPrefrenceUtil.setStringValue(Constant.USER_ID, bmobUser.objectId);
        SharedPrefrenceUtil.setStringValue(Constant.USER_NAME, bmobUser.username);
        Navigator.pop(context, [bmobUser.username,bmobUser.objectId]);
      }).catchError((e) {
        Toast.toast(context, BmobError
            .convert(e)
            .error);
      });
      setState(() {
        _getData=!_getData;
      });
    }else{
      //注册模式
      await user.register().then((registered){
        print(registered);
        _passController.clear();
        Toast.toast(context, "注册成功，请登录");
      }).catchError((e){
        Toast.toast(context, BmobError
            .convert(e)
            .error);
      });
      setState(() {
        _getData=!_getData;
        _isLogin=!_isLogin;
      });
    }
  }

}